//
//  LZTComposePictureView.swift
//  LZTWeibo
//
//  Created by Yin jianxun on 16/8/17.
//  Copyright © 2016年 YinJianxun. All rights reserved.
//

import UIKit

//可重用cell的标识符
private let LZTComposePictureViewCellId = "LZTComposePictureViewCell"

class LZTComposePictureView: UICollectionView {
    
    //保存选中图片的 数组
    var imageList: [UIImage] = [UIImage]()
    
    //closure01  用于告知composeVC 店家加号 图片时也要跳转 相册
    var closure: (()->())?
    

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //供外界调用 设置image 添加到imageList
    func addImages(image: UIImage) {
        
        //点击添加图片时在显示
        self.hidden = false
        
        //传入图片加入数组
        imageList.append(image)
        //刷新UI
        reloadData()
    }
    
    //设置试图
    func setupUI() {
        
        //一旦创建后先隐藏，点击添加图片时在显示
        self.hidden = true
        
        backgroundColor = UIColor.whiteColor()
        
        //注册cell
        self.registerClass(LZTComposePictureViewCell.self, forCellWithReuseIdentifier: LZTComposePictureViewCellId)
        
        //设置代理
        dataSource = self
        delegate = self
        //设置layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //Item间距
        let cellMargin: CGFloat = 5
        //item的宽高
        let cellWH: CGFloat = (SCREENW - 20 - cellMargin * 2) / 3
        //设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        //设置垂直水平间距
        layout.minimumLineSpacing = cellMargin
        layout.minimumInteritemSpacing = cellMargin
    }
    
}

extension LZTComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //0张和9张得时候，都不显示 加号 图片
        //1-8的时候，后面对应的都可以加上 加号 图片
        let count = imageList.count
        
        if count == 0 || count == 9 {
            return count
        }
        
        return imageList.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LZTComposePictureViewCellId, forIndexPath: indexPath) as! LZTComposePictureViewCell
        
        //当item和数组的count值相等时，代表可以在当前最后一个item后面加上 加号 图片
        if imageList.count == indexPath.item {
            
            //不赋值
            cell.image = nil
        }else {
            
            //为cell显示图片赋值
            cell.image = imageList[indexPath.item]
            
            //删除按钮的闭包 02-04
            cell.closure = {[weak self] in
                //每一个Item对应一个已经实例cell的闭包
                self?.imageList.removeAtIndex(indexPath.item)
                
                if self?.imageList.count == 0 {
                    //一旦创建后先隐藏，点击添加图片时在显示
                    self?.hidden = true
                }
                
                //刷新UI
                self?.reloadData()
            }
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        //如果有加号图片的显示，点击 加号图片时也要跳转相册，告知composeVC跳转 闭包
        if imageList.count == indexPath.item {
            
            //closure03 执行
            closure?()
        }
    }
}

//自定义cell
class LZTComposePictureViewCell: UICollectionViewCell {
    
    //闭包 传入pictureView.imageList用于删除数组的元素
    var closure:(()->())?
    
    //供外界调用 传入image
    var image: UIImage? {
    
        didSet{
            
            if image == nil {
                //加号 图片的显示
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                //隐藏 删除按钮
                deleteBtn.hidden = true
                
            }else {
                
                //正常图片的赋值
                bgImageView.image = image
                //解决cell的复用问题 ：因为有的cell已经设置过highlightedImage，导致所有的cell都有了highlightedImage
                bgImageView.highlightedImage = nil
                //隐藏 删除按钮
                deleteBtn.hidden = false
            }

        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //删除按钮的点击事件
    func deleteImageAction() {
        
        //closure03
        closure?()
    }
    
    //设置试图
    func setupUI() {
        
        //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteBtn)
        //添加约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.trailing.equalTo(contentView)
        }
    }
    
    //懒加载 控件
    private lazy var bgImageView: UIImageView = UIImageView()
    
    //懒加载 删除按钮
    private lazy var deleteBtn: UIButton = {
        
        let button = UIButton()
        //按钮的点击事件
        button.addTarget(self, action: #selector(LZTComposePictureViewCell.deleteImageAction), forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()
    
}

